package com.sh.data.engine.web.exception;

import com.sh.data.engine.common.constants.HttpStatus;
import com.sh.data.engine.common.constants.code.BizCodes;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.web.webapi.controller.base.response.RestResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author: mengzheng.mhc
 * @date: 2024/5/27 9:26
 */
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({BusinessException.class})
    public RestResponseEntity<Object> handleBusinessException(BusinessException exception) {
        return RestResponseEntity.error(exception.getCode(), exception.getHttpStatusCode(), exception.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public RestResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        // 从异常中获取字段错误信息
        List<String> fieldErrorMessages = exception.getBindingResult().getFieldErrors().stream()
            .map(FieldError::getDefaultMessage)
            .toList();
        String errorMessage = String.join("， ", fieldErrorMessages);
        return RestResponseEntity.error(BizCodes.REQUEST_ERROR.getCode(), HttpStatus.BAD_REQUEST.value(), errorMessage);
    }
}
